/**
 * @description 备份-控制器
 * @since 2019-11-12
 * @author Rid King
*/

const fs = require('fs')
const tar = require('tar')
const ox = require('@daelui/oxjs')
const { dater, strer, filer } = require('@daelui/oxkit')
const Service = require('./service.js')

class Controller extends ox.Controller {
  /**
   * @function 构造方法
  */
  constructor (args) {
    super(args)
    // 服务
    this.$service = new Service(args)
  }

  /**
   * @function 增删改过滤
  */
  filterAction ({ name, action }) {
    if (/insert/.test(name)) {
      let name = dater.format(new Date(), 'yyyyMMddHHmmss') + strer.urid(4) + '.tar.gz'
      action.params.path = name
    }
    else if (/delete|deleteAll/.test(name)) {
      this.deleteStoreData(action)
    }
    return { success: 1 }
  }

  /**
   * @function 增删改事件触发
  */
  emit (name, action, res) {
    super.emit(name, action, res)
    res = res || {}
    if (res.success && /insert/.test(name)) {
      this.reStoreData(action)
    }
  }

  // 备份数据
  reStoreData (action) {
    let params = action.params
    let config = this.route.scope.CONFIG
    let dbPath = config.db.hostname
    let backupPath = config.constant.backupPath
    this.tarDirectory(dbPath, backupPath + '/' + params.path)
  }

  // 压缩目录
  tarDirectory (inputFile, outputFile) {
    outputFile = outputFile.replace(/\/+$/, '')
    let outputPath = outputFile.replace(/\/\w+?(\.\w+)+$/i, '')
    if (!fs.existsSync(outputPath)) {
      filer.buildPath(outputPath)
    }
    if (!/\.\w+$/i.test(outputFile)) {
      outputFile = outputFile + '/' + dater.format(new Date(), 'yyyyMMddHHmmss') + strer.urid(4) + '.tar.gz'
    }
    tar.c(
      {
        gzip: true, // 如果想要gzip压缩
        file: outputFile // 输出文件路径
      },
      [inputFile]
    )
    .then(() => {
      // console.log('压缩成功')
    })
    .catch((error) => {
      console.error('压缩失败:', error)
    })
  }

  // 删除备份数据
  async deleteStoreData (action) {
    let params = action.params || []
    params = params.length ? params : [-9999]
    let res = await this.queryAll({}, {
      action: {},
      query: {},
      params: {
        id: params
      },
      excute: {
        operators: [
          { field: 'id', operator: 'IN' }
        ]
      }
    })
    let list = res.data
    list = Array.isArray(list) ? list : []
    list = list.filter(item => item.path)
    let config = this.route.scope.CONFIG
    let backupPath = config.constant.backupPath
    backupPath = backupPath.replace(/\/+$/, '')
    list.forEach(item => {
      filer.deleteAll(backupPath + '/' + item.path)
    })
  }
}

module.exports = Controller